package com.wnzt.baszh.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wnzt.baszh.ca.NetcaPKI;
import com.wnzt.baszh.entity.Tsysuser;
import com.wnzt.baszh.service.IUserService;
import com.wnzt.baszh.util.common.ConstantsUtils;
import com.wnzt.baszh.util.common.GlobalStatic;

@Controller
@RequestMapping("/")
public class AccessController {
    
    @Autowired
    private IUserService userService;

    @RequestMapping("/login")
    public String toLogin() {
        return "login/login";
    }
    
    @RequestMapping("/viewer")
    public String viewer(HttpServletRequest request) {
    	request.setAttribute("file", request.getParameter("file"));
    	request.setAttribute("title", request.getParameter("title"));
        return "MedicalCheckManage/viewer";
    }
   
    @RequestMapping("/loginCA")
    public String loginCA(HttpSession session) {
    	//步骤1：后台产生的6位长的随机数,并放到session中
    	int number = (int) (Math.random() * 100000 + 100000); //
    	String ticket = "" + number;
    	session.setAttribute("ticket", ticket);
        return "login/ca_login";
    }
    
    
    @RequestMapping("/index")
    public String toIndex() {
        return "main/index";
    }
    
    
    /**
     * 登录
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/logon")
    @ResponseBody
    public Object logon(HttpServletRequest request,HttpServletResponse response, Model model) {
        HttpSession session = request.getSession();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        Map<String,Object> result = new HashMap<String, Object>();
    	
        if(StringUtils.isBlank(username)&&StringUtils.isBlank(password)){
            result.put("success", false);
            result.put("msg", "用户名和密码不能为空！");
        }
        if(StringUtils.isBlank(username)){
            result.put("success", false);
            result.put("msg", "用户名不能为空！");
        }
        if(StringUtils.isBlank(password)){
            result.put("success", false);
            result.put("msg", "密码不能为空！");
        }
        Tsysuser user = userService.checkUser(username, password);
        if(user != null){
            session.setAttribute(GlobalStatic.USER_SESSION_ID, user.getFcode());
            session.setAttribute(GlobalStatic.USER_SESSION_OBJECT, user);
            model.addAttribute(GlobalStatic.USER_SESSION_OBJECT, user);
            result.put("success", true);
            result.put("url", "/index");
        }else{
            result.put("success", false);
            result.put("msg", "用户名或密码不正确！");
        }
        return JSONObject.fromObject(result);
    }
    
    /**
     * 登录-CA验证
     * @author [lv tang wei]
     * Describe:
     * @param request
     * @param response
     * @param model
     * @return
     * [2017年6月28日]
     */
    @RequestMapping("/logonCA")
    @ResponseBody
    public Object logonCA(HttpServletRequest request,HttpServletResponse response, Model model) {
        HttpSession session = request.getSession();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //前台证书签名结果
        String ticketSigned = request.getParameter("ticketSigned")==null?null: request.getParameter("ticketSigned");
        //后台产生的随机数
        String ticket = request.getSession().getAttribute("ticket")==null?null:(String) request.getSession().getAttribute("ticket");
        
        Map<String,Object> result = new HashMap<String, Object>();
        
        net.netca.pki.Certificate oCert = null;
    	try {
    		long a=System.currentTimeMillis();
    		//验证签名的有效性；
    		oCert = NetcaPKI.verifySignedData(ticket, ticketSigned, true);
    		System.out.println("执行耗时 : "+(System.currentTimeMillis()-a)/1000f+" 秒 ");
    		
    	} catch (Exception e) {
    		System.out.println("登录失败，错误信息为：" + e.getMessage());
    		 result.put("success", false);
             result.put("msg", e.getMessage());
             return JSONObject.fromObject(result);
    	}
    	
        if(StringUtils.isBlank(username)&&StringUtils.isBlank(password)){
            result.put("success", false);
            result.put("msg", "用户名和密码不能为空！");
        }
        if(StringUtils.isBlank(username)){
            result.put("success", false);
            result.put("msg", "用户名不能为空！");
        }
        if(StringUtils.isBlank(password)){
            result.put("success", false);
            result.put("msg", "密码不能为空！");
        }
        Tsysuser user = userService.checkUserCA(username, password);
        if(user != null){
            session.setAttribute(GlobalStatic.USER_SESSION_ID, user.getFcode());
            session.setAttribute(GlobalStatic.USER_SESSION_OBJECT, user);
            model.addAttribute(GlobalStatic.USER_SESSION_OBJECT, user);
            result.put("success", true);
            result.put("url", "/index");
            //登录验证成功之后，删除原文
            request.getSession().removeAttribute("ticket");
        }else{
            result.put("success", false);
            result.put("msg", "用户名或密码不正确！");
        }
        return JSONObject.fromObject(result);
    }
    
    /**
     * 退出登记
     * @param request
     * @return
     */
    @RequestMapping("/outLogin")
    @ResponseBody
   public Object outLogin(HttpServletRequest request){
	   Map<String,Object> map = new HashMap<String, Object>();
	   HttpSession session = request.getSession();
	   if(session != null){
		   session.removeAttribute(GlobalStatic.USER_SESSION_ID);
		   session.removeAttribute(GlobalStatic.USER_SESSION_OBJECT);
		   session.invalidate();
		   map.put("success", true);
	   }else{
		   map.put("success", false);
	   }
	   return map;
   }
    
    /**
     * 获取系统菜单
     * @param request
     * @return
     */
   @RequestMapping("/getMenu")
   @ResponseBody
   public Object getMenu(HttpServletRequest request){
	 //获取当前用户
	Tsysuser user = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
	String fgroupcode = user.getFgroupcode();//用户组编号
	//Map<String,Object> map = new HashMap<String,Object>();
	List<Map<String,Object>> listResult = new ArrayList<Map<String,Object>>();  //存放父节点
	List<Map<String,Object>> list =userService.getmenulistByUser(fgroupcode);
/*	for(int i=0;i<list.size();i++){
		Map<String,Object> ma= list.get(i);
		String ffather = (String) ma.get("ffather");
		//判断如果ffather为空，就为父节点
		if(ConstantsUtils.isBank(ffather)){
			ma.put("children", new ArrayList<Map<String,Object>>());
			listResult.add(ma);
		}else{
			//获取子节点，然后再与父节点中的编号做比较，找出子节点对应的父节点
			for(int j=0;j<listResult.size();j++){
				String fcode = (String) listResult.get(j).get("fcode");
				if(fcode.equals(ffather)){
					List li = (List) listResult.get(j).get("children");
					li.add(ma);
				}
			}
		}
	}
	*/
	 List<Map<String, Object>> nodeList = new ArrayList<Map<String,Object>>();
     for (Map<String, Object> map : list) {
     	String fatherCode = (String) map.get("ffather");  // 父节点编号
     	boolean fatherNode = (Boolean) map.get("fhavefather");   // 是否有父节点  true: 表示有父节点
     	boolean childNode = (Boolean) map.get("fhavechildren");  // 是否有子节点  true: 表示有子节点
     	
         // 当节点有子节点时，给节点添加子节点list列表，用来保存子节点
     	if (childNode) {
 			map.put("children", new ArrayList<Map<String, Object>>());
 		}
     	
     	if (!fatherNode) {  // 当节点没有父节点时，表示该节点是顶级节点，要将其加到节点列表中
     		nodeList.add(map);
     	} else {  // 当节点有父节点时, 表示其是子节点，找到该节点的父节点，将该节点添加到其父节点的子节点列表中
     		for (Map<String, Object> map2 : list) {
     			String code = (String) map2.get("fcode");
     			if (fatherCode.equals(code)) {
     				@SuppressWarnings("unchecked")
						List<Map<String, Object>> childNodeList = (List<Map<String, Object>>) map2.get("children");
     				childNodeList.add(map);
     				break;
     			}
     		}
     	}
     }
	return nodeList;
 }
   
}